<?php

class Rider extends MY_Controller
{
	private $base_url;

	public function __construct()
	{
		parent::__construct();
		$this->load->model('rider_model');
		$this->load->helper('url');
		$this->load->library('session');
		$this->base_url = array('base_url' => $this->config->item('base_url'));
		$this->assign('base_url', $this->base_url);
	}

	public function index()
	{
		if(isset($_SESSION['id']) && $_SESSION['type'] == 2){
			$result = $this->rider_model->get_unreceived_order();
			$this->assign('orders', $result);
			$this->display('rider/index.tpl');
		} else{
			redirect('user/login');
		}
	}

	public function myorder()
	{
		if(isset($_SESSION['id']) && $_SESSION['type'] == 2){
			if (!empty($_POST['submit']) && $_POST['submit'] === 'finish' && !empty($_POST['id'])){
				$result = $this->rider_model->finish_order($_POST['id']);
				if ($result){
					$this->assign('time', $result);
					$this->assign('oid', $_POST['id']);
					$this->display('success/finish.tpl');
				}else{
					echo "<script>alert('接单错误')</script>";
				}
			}else {
				$result = $this->rider_model->get_my_unfinished_order($_SESSION['id']);
				$this->assign('orders', $result);
				$this->display('rider/myorder.tpl');
			}
		} else{
			redirect('user/login');
		}
	}

	public function order($id = NULL)
	{
		if(isset($_SESSION['id']) && $_SESSION['type'] == 2){
			if (!empty($_POST['submit']) && $_POST['submit'] === 'ack' && !empty($_POST['id'])){
				$result = $this->rider_model->receive_order($_SESSION['id'], $_POST['id']);
				if ($result){
					$this->display('success/receive_order.tpl');
				}else{
					echo "<script>alert('接单错误')</script>";
				}
			}else{
				$result = $this->rider_model->view_order_detail($id);
				$this->assign('details', $result);
				$this->display('rider/order.tpl');
			}
		} else{
			redirect('user/login');
		}
	}

	public function register()
	{
		if ($_SERVER['REQUEST_METHOD'] === 'POST'){
			if (!empty($_POST['password']) && !empty($_POST['phone_number'])){
				if (strlen($_POST['phone_number']) === 11){
					$password = $_POST['password'];
					$phone_number = $_POST['phone_number'];
					$result = $this->rider_model->insert_rider($password, $phone_number);
					if ($result > 0){
						$this->assign('id', $result);
						$this->display('success/rider_reg.tpl');
					}else{
						echo "<script>alert('联系电话已被注册');</script><script>history.back();</script>";
					}
				}else{
					echo "<script>alert('电话格式有误');</script><script>history.back();</script>";
				}
			}else{
				echo "<script>alert('请完善信息');</script><script>history.back();</script>";
			}
		}else{
			$this->display('rider/register.tpl');
		}
	}
}
